package array;

public class leetCode41_firstMissingPositive {
    public static void main(String[] args) {
        leetCode41_firstMissingPositive a = new leetCode41_firstMissingPositive();
        int[] arr = {1,3,-1,4};
        int i = a.firstMissingPositive(arr);
        System.out.println(i);
    }

    public int firstMissingPositive(int[] nums) {
        int len = nums.length;

        for (int i = 0; i < len; i++) {
            while (nums[i] > 0 && nums[i] < len && nums[nums[i] - 1] != nums[i]){
                swap(nums,nums[i] - 1,i);
            }
        }
        for (int i = 0; i < len; i++) {
            if(nums[i] != i + 1){
                return i + 1;
            }
        }
        return len + 1;
    }

    public int firstMissingPositive2(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            while (nums[i] > 0 && nums[i] < len && nums[nums[i] - 1] != nums[i]){
                swap(nums,i,nums[i] - 1);
            }
        }

        for (int i = 0; i < len; i++) {
            if(nums[i] != i + 1){
                return i + 1;
            }
        }
        return len + 1;

    }

    private void swap(int[] nums,int a,int b){
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}
